const { executeQuery, baseQuery } = require('./mongo_util')
const collectionName = "repair";

function addrepair(carts, onRetGot, onErrGot) {
    let data = new Date()
    let id = data.getTime();
    console.log("carts", carts);
    const list=carts.data
    list.id = id;
    executeQuery(collectionName, (collection, callback) => {
        collection.insertOne({...list}).then((res) => {
            console.log("res=",res);
            onRetGot(res);
            callback()
        })
            .catch((err) => {
                onRetGot(err);
                callback();
        })
    })
}

function updaterepair(carts, onRetGot, onErrGot) {
    let id = carts.id;
    let data = carts.data
    

    executeQuery(collectionName, (collection, callback) => {
        collection.update({"id":id},{$set:{...data}}).then((res) => {
            console.log("res=",res);
            onRetGot(res);
            callback()
        })
            .catch((err) => {
                onRetGot(err);
                callback();
        })
    })
}



// 删除购物车商品
function deleterepair(carts, onRetGot, onErrGot) {
    let userid = carts.userid;
    let goodsid = carts.goodsid;
    executeQuery(collectionName, (collection, callback) => {
        collection.deleteMany({ userid: userid, goodsid: { $in: goodsid } }).then((res) => {
            console.log("res=",res);
            onRetGot(res);
            callback()
        })
            .catch((err) => {
                onRetGot(err);
                callback();
        })
    })
}

//获取所有维修记录


function selectrepair(carts, onRetGot, onErrGot) {
    let limit = carts.size*1;
    let skip = (carts.page - 1) * limit;
    console.log(limit,skip);
    executeQuery(collectionName, (collection, callback) => {
        collection.find({}).count().then(async(res) => {
            let obj = {};
            obj.total = res;

            await collection.find({}).skip(skip).limit(limit).toArray().then((bbq => {
                obj.data = bbq;
            }))
            onRetGot(obj);
            callback()
        })
            .catch((err) => {
                onRetGot(err);
                callback();
        })
    })
}
//根据条件获取数据
function list(carts,onRetGot, onErrGot) {
    const field = carts.field;
    const inputx = carts.input;
    // console.log("jiayou ",field,inputx);
    executeQuery(collectionName, (collection, callback) => {
        collection
            .find({ [field]:inputx}).toArray()
            .then((result) => {
                onRetGot(result);
                callback();
            })
            .catch((err) => {
                onErrGot(err);
                callback();
            });
    });
}



module.exports = {
    addrepair,
    updaterepair,
    deleterepair,
    selectrepair,
    list
}